<template>
  <el-tree class="custom_tree" :data="func.allFuncsTreeData" :expand-on-click-node="false"
    :props="{ label: 'func_name', children: 'children' }" default-expand-all>
    <template #default="{ data, data: { func_id, func_name, func_key, children } }">
      <div class="custom-tree-node">
        <span :class="{ leaf: func_key !== '' }">
          <el-icon style="vertical-algin: middle" :size="20" v-if="func_key != ''" color="#3377cc">
            <Paperclip />
          </el-icon>{{ func_name }}
        </span>
        <span>
          <el-button type="primary" size="default" @click="beginAdd(data)" text v-if="func_key === ''"
            :icon="Plus">新增</el-button>
          <el-button type="primary" size="default" @click="beginUpdate(data)" text v-if="![0, 1, 2].includes(func_id)"
            :icon="Edit">修改</el-button>
          <el-button type="primary" size="default" @click="removeHandler(func_id)" text
            v-if="![0, 1, 2].includes(func_id)" :disabled="func_key === '' && children !== undefined"
            :icon="Delete">删除</el-button>
        </span>
      </div>
    </template>
  </el-tree>
  <el-dialog title="功能编辑" v-model="isEdit" width="30%">
    <el-form>
      <el-form-item label="功能类型:">
        <el-radio-group v-model="isLeaf" :disabled="
          model.func_id !== 0 &&
          model.func_key === '' &&
          func.allFuncs.some((item) => item.func_fid === model.func_id)
        ">
          <el-radio :label="false"> 非叶子节点 </el-radio>
          <el-radio :label="true"> 叶子节点 </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="父级功能">
        <el-cascader :disabled="model.func_id === 0" v-model="model.func_fid" :options="noLeafFuncsTreeData" :props="{
          label: 'func_name',
          value: 'func_id',
          children: 'children',
          checkStrictly: true,
          emitPath: false,
        }">
        </el-cascader>
      </el-form-item>
      <el-form-item label="功能名称">
        <el-input placeholder="请输入功能名称.." v-model.trim="model.func_name">
        </el-input>
      </el-form-item>
      <el-form-item label="绑定组件:" v-if="isLeaf">
        <el-select v-model="model.func_key">
          <el-option label="-请选择-" value=""></el-option>
          <el-option v-for="item in Object.keys(dashboard.funcMap)" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">确定</el-button>
        <el-button @click="isEdit = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed, watch } from "vue";

import { ElMessageBox, ElMessage } from "element-plus";
import { useDashboard, useFunc } from "@/store";
import arrayToTree from "@/utils/arrayToTree";
import { Plus, Edit, Delete, Paperclip } from "@element-plus/icons-vue";


const dashboard = useDashboard();
const func = useFunc()
const isEdit = ref<boolean>(false);
const isLeaf = ref<boolean>(false);
const model = reactive<HttpPayload.Func>({
  func_id: 0,
  func_name: "",
  func_key: "",
  func_fid: -1,
});



const noLeafFuncsTreeData = computed<Array<Vm.FuncNode>>(() => {
  return [
    {
      func_id: 0,
      func_name: "Root",
      func_key: "",
      func_fid: -1,
      children: arrayToTree(
        func.allFuncs.filter((item) => item.func_key === ""),
        "func_id",
        "func_fid"
      ),
    },
  ];
});
watch(isLeaf, (newValue) => {
  if (!newValue) model.func_key = "";
});
onMounted(async () => {
  try {
    func.init();
  } catch (e) {
    /**/
  }
});

const removeHandler = async (func_id: number) => {
  try {
    //问用户是不是确定删除
    await ElMessageBox.confirm("真删", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // 发ajax从数据库中删除功能
    await func.remove(func_id)
    //从allFuncs中删除功能,更新页面
    ElMessage({ type: "success", message: "功能删除成功" });
  } catch (e) {
    /**/
  }
};
const beginAdd = async (func: Vm.FuncNode) => {
  try {
    model.func_id = 0;
    model.func_name = "";
    model.func_key = "";
    model.func_fid = func.func_id;
    isLeaf.value = false;

    isEdit.value = true;
  } catch (e) {
    /**/
  }
};
const beginUpdate = (func: Vm.FuncNode) => {
  model.func_id = func.func_id;
  model.func_name = func.func_name;
  model.func_key = func.func_key;
  model.func_fid = func.func_fid;
  isLeaf.value = func.func_key !== "";

  isEdit.value = true;
};
const save = async () => {
  try {
    await func[model.func_id === 0 ? 'add' : 'update'](model);
    isEdit.value = false;
    ElMessage({ type: 'success', message: "功能编辑成功" })
  } catch (e: any) { ElMessage({ type: "error", message: e.message }) }
}
</script>

<style scoped lang="stylus">
.el-tree
  width 700px
.custom-tree-node
  flex-grow 1
  display flex
  justify-content space-between
  algin-items center
// .leaf
</style>
